package com.cheetah.handler;

import com.cheetah.annotation.Handler;
import com.cheetah.constants.AttributeKeyConstants;
import com.cheetah.controller.protobuf.ProtobufHandlerManager;
import com.cheetah.dispatcher.RequestMapping;
import com.cheetah.protocol.ErrorCode;
import com.cheetah.protocol.Request;
import com.cheetah.protocol.RequestHeader;
import com.cheetah.protocol.Response;
import com.cheetah.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.AttributeKey;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author Administrator
 * @Date 2019/9/14
 * @Version V1.0
 * @Description:
 **/

@Component
@Handler(order = 10)
@ChannelHandler.Sharable
public class TokenFilterHandler extends SimpleChannelInboundHandler<Request> {

    @Autowired
    private ProtobufHandlerManager manager;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Request msg) throws Exception {
        RequestHeader header = msg.getRequestHeader();
        String type = (String)ctx.channel().attr(AttributeKey.valueOf(AttributeKeyConstants.ATTRIBUTE_KEY_TYPE)).get();
        //根据消息类型，利用java反射机制进行request的分发调用
        RequestMapping requestMapping = manager.requestMappings().get(type);

        if(requestMapping.isAuth()){
            String token = header.getToken();
            if(StringUtils.isBlank(token)){
                ctx.channel().writeAndFlush(Response.builder()
                        .errorCode(ErrorCode.ERROR_CODE_401)
                        .errorMsg("token不能为空！")
                        .success(false)
                        .build()
                );
            }else{
                Jws<Claims> claimsJws =  TokenUtil.parseToken(token);
                Claims claims = claimsJws.getBody();
                claims.forEach((k,v) -> {
                    System.out.println(k + v);
                });
            }
        }

        ctx.fireChannelRead(msg);
    }
}
